<?php
namespace control;
/*
*档案归还类
*/


class archiveReturnClass extends adIndexClass
{
    private const title = '档案归还';
    private const page = 'archiveReturn';
    private const table = 'archive_borrow';
    private const tableMx = 'archive_borrow_detail';
    private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'borrowedSearch':
                $tr = [
                    'returnState'          => [
                        'name'  => '借阅状态',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'typeId' => [
                        'name'  => "档案分类",
                        'width' => 100,
                    ],
                    'cNo'  => [
                        'name'  => "归档号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '题名',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 100,
                    ],
                    'stName'          => [
                        'name'  => '申请借阅人',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'company'          => [
                        'name'  => '借阅人单位',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '借阅方式',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'copyNum'          => [
                        'name'  => '复印份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'application'          => [
                        'name'  => '借阅用途',
                        'width' => 150,
                    ],
                    'borrowDate'          => [
                        'name'  => '借出日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'exReturnDate'          => [
                        'name'  => '应还日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'returnDate'          => [
                        'name'  => '实际归还日期',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'returnState'          => [
                        'name'  => '借阅状态',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'typeId' => [
                        'name'  => "档案分类",
                        'width' => 100,
                    ],
                    'cNo'  => [
                        'name'  => "归档号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '题名',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 150,
                    ],
                    'stName'          => [
                        'name'  => '申请借阅人',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'company'          => [
                        'name'  => '借阅人单位',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '借阅方式',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'copyNum'          => [
                        'name'  => '复印份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'application'          => [
                        'name'  => '借阅用途',
                        'width' => 150,
                    ],
                    'borrowDate'          => [
                        'name'  => '借出日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'exReturnDate'          => [
                        'name'  => '应还日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'returnDate'          => [
                        'name'  => '实际归还日期',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        $title = "借出日期";
        if ($workFlow =='已归还'){
            $title = "归还日期";
        }
        return $this->tableShow([
            [
                [
                    "分类" => selectMultiple(array("name" => "typeId", 'table' => "archive_type", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                    "题名"     => text(array("name" => "name")),
                    '归档号' => text(array("name" => "orderNo")),
                ],
                [
                    '存放位置'   => selectMultiple(array("name" => "locationId", 'table' => "archive_cabinet", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                    "申请借阅人"     => text(array("name" => "stName")),
                    "借阅人单位"     => text(array("name" => "company")),
                ],
                [
                    "借阅用途"     => text(array("name" => "application")),
                    "借阅方式" => select(array("name" => "type", "option" => explode("，", para("borrowType")))),
                    $title   => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待归还');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "<span onclick=\"layer('{$this->get('cla')}','back',{})\" class='spanButton'>归还</span>\n";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "a.company" => $this->post('company'),//借阅人单位
            "a.stName" => $this->post('stName'),//标题
            "c.orderNo" => $this->post('cNo'),
            "c.name" => $this->post('name'),
            "b.application" => $this->post('application'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '已借阅',
            'b.returnState' => '待归还',
            "c.typeId" => $this->post('typeId'),//公文种类
            "b.type" => $this->post('type'),
            "c.locationId" => $this->post('locationId'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "b.borrowDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.applyDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'field' => "b.*,a.company,c.typeId,c.name,c.orderNo as cNo,c.locationId,a.stName,a.state,a.applyDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "draftId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "draftId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=archiveBorrow&fun=detail&id=" . $array['orderId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = dossierClass::getTypeName($array['typeId']);
                        break;
                    case "locationId":
                        $row[] = dossierClass::getPosititonName($array['locationId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'single' => $where,
            'field'  => "ifnull(sum(b.copyNum),0) as copyNum",
        ]);
        $total    = [
            'copyNum'        => $totalQuery['copyNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function borrowedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已归还');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function borrowed(): string
    {
        $html = $this->borrowedOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已归还
     * @return bool|string
     */
    public function borrowedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "a.company" => $this->post('company'),//借阅人单位
            "a.stName" => $this->post('stName'),//标题
            "c.orderNo" => $this->post('cNo'),
            "c.name" => $this->post('name'),
            "b.application" => $this->post('application'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '已借阅',
            'b.returnState' => '已归还',
            "c.typeId" => $this->post('typeId'),//公文种类
            "c.locationId" => $this->post('locationId'),
            "b.type" => $this->post('type'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "b.returnDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.applyDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'field' => "b.*,a.company,c.typeId,c.name,c.orderNo as cNo,c.locationId,a.stName,a.state,a.applyDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("abolishedForm", "abolishedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "abolishedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=archiveBorrow&fun=detail&id=" . $array['orderId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = dossierClass::getTypeName($array['typeId']);
                        break;
                    case "locationId":
                        $row[] = dossierClass::getPosititonName($array['locationId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join archive_file as c on c.id = b.fileId",
            'single' => $where,
            'field'  => "ifnull(sum(b.copyNum),0) as copyNum",
        ]);
        $total    = [
            'copyNum'        => $totalQuery['copyNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 归还
     */
    public function back(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "归还日期：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
        )));
        //返回
        return $this->layer(array("title" => "归还", "height" => 150, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 归还
     */
    public function backEdit(): bool|string
    {
        $idArr = $this->post('draftId');
        if (static::is_null_array($idArr)) {
            $json['warn'] = "请选择需要归还的档案";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择归还日期';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $mx = query(self::tableMx, "id = '$id'");
                $archive_file = query('archive_file', "id = '$mx[fileId]'");
                if ($mx['workFlow'] != '已借阅') {
                    $text .= $this->control['name'] . "归还档案【{$archive_file['name']}】， id：{$id} 失败：不是已借阅状态<br>";
                } else {
                    $warn = update(array('table' => self::tableMx, 'field' => ['returnState' => '已归还', 'returnDate' => $this->post('signTime')], 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        update(array('table'=>'archive_file','field'=>['fileState'=>0],'where'=>"id = '$archive_file[id]'"));
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "归还了档案【{$archive_file['name']}】， id：{$id}成功，归还日期:{$this->post('signTime')}<br>";
                    } else {
                        $text .= $this->control['name'] . "归还了档案【{$archive_file['name']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功归还了{$x}个档案，详情请查看系统日志";
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


}
